<?php

namespace app\admin\controller\mental;

use app\common\controller\Backend;
use app\admin\model\mental\Testson;
use app\admin\model\mental\Result;
use app\admin\model\mental\Component;
use think\Db;
use think\Exception;
use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 测试管理
 *
 * @icon fa fa-circle-o
 */
class TestMain extends Backend
{

    /**
     * TestMain模型对象
     * @var \app\admin\model\mental\TestMain
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mental\TestMain;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("payModeList", $this->model->getPayModeList());

        $this->view->assign("dimensionImageArr", config('site.dimensionImageArr'));


        // $versionType = config('site.versionType');
        $this->view->assign("gaugeConfig1", config('site.gaugeConfig1'));
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('Category')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Undocumented function
     * 编辑界面
     * @return void
     */
    public function edit_result($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $testson = new Testson();
        $question = $testson->with('Question')->where('main_id', '=', $ids)->select();
        $restModel = new Result();
        $result = $restModel->where('main_id', '=', $ids)->find();
        $question_ids = [];
        foreach ($question as $val) {
            $question_ids[] = $val['question_id'];
        }

        // halt(collection($question)->toArray());die;
        $this->view->assign("question", $question);
        $this->view->assign("question_ids", json_encode($question_ids));
        $this->view->assign("result", $result);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * Undocumented function
     * 编辑量表的结果
     * @return void
     */
    public function component($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $component_ids = explode(',', $params['component_id']);
            $status = false;
            //问题
            $question_ids = [];
            //结果
            $result = [];

            foreach ($component_ids as $key => $value) {
                $status = !isset($params[$key]);
                if ($status) {
                    break;
                }
                //问题处理
                $question_id = $params[$key]['question_id'];
                foreach ($question_id as $q_id) {
                    $question_ids[] = [
                        'component_id' => $value,
                        'id' => $q_id
                    ];
                }
                $result[] = [
                    'component_id' => $value,
                    'content' => $params[$key]['result'],
                    'type' => $params[$key]['type']
                ];
            }
            if ($status) {
                $this->error('数据格式错误！');
            }
            try {
                Db::startTrans();
                //处理问题
                $testson = new Testson();
                $testson->saveData($question_ids, $ids);
                //处理结果
                foreach ($result as $item) {
                    $resModel = new Result();
                    $resModel->saveData($item['content'], $ids, $item['component_id'], $item['type']);
                }
                Db::commit();
                $this->success();
            } catch (Exception $e) {
                Db::rollback();
                $this->error(__($e->getMessage()), $e->getCode());
            }
        }

        $testson = new Testson();
        $sons = $testson->field('count(*) total,component_id')->where('main_id', '=', $ids)->group('component_id')->select();
        $list = [];
        $component_ids = [];
        foreach ($sons as $key => $value) {
            $component = (new Component())->get($value['component_id']);
            if (empty($component)) {
                continue;
            }
            $component_ids[] = $value['component_id'];
            $result = (new Result())->where('main_id', $ids)->where('component_id', $value['component_id'])->find();
            $question = $testson->with('Question')->where('main_id', $ids)->where('component_id', $value['component_id'])->select();
            $list[] = [
                'id' => $value['component_id'],
                'title' => $component['name'],
                'type' => $result['type'],
                'question' => $question,
                'result' => json_decode($result['content'], true)
            ];
        }
        $this->assign('lists', json_encode($list));
        $this->assign('component_ids', join(',', $component_ids));
        return $this->view->fetch();
    }

    /**
     * Undocumented function
     * 编辑更多信息
     * @return void
     */
    // public function edit_info($ids = null)
    // {
    //     $data = $this->model->get($ids);
    //     if (!$data) {
    //         $this->error(__('No Results were found'));
    //     }
    //     //判断
    //     $post = $this->request->post();
    //     // $this->error('','',$post) ;     
    //     if (!isset($post['row'])) {
    //         $this->error(__('No Results were found'));
    //     }
    //     $post['result'] = json_decode($post['result'], true);
    //     $key = [];
    //     foreach ($post['result'] as $val) {
    //         if (isset($val['key'])) {
    //             $vk = (int) $val['key'];
    //             $key[$vk] = $vk;
    //         }
    //     }
    //     if (count($key) > 0 && count($key) != count($post['result'])) {
    //         $this->error(__('Invalid parameters'));
    //     }
    //     try {
    //         Db::startTrans();
    //         //处理问题
    //         $testson = new Testson();
    //         $testson->saveData($post['row'], $ids);
    //         //处理结果
    //         $resModel = new Result();
    //         $resModel->saveData($post['result'], $ids);
    //         Db::commit();
    //         $this->success();
    //     } catch (Exception $e) {
    //         Db::rollback();
    //         $this->error(__($e->getMessage()), $e->getCode());
    //     }
    // }
    public function edit_info($ids = null)
    {
        $data = $this->model->get($ids);
        if (!$data) {
            $this->error(__('No Results were found'));
        }
        //判断
        $post = $this->request->post();
        // $this->error('','',$post) ;     
        if (!isset($post['row'])) {
            $this->error(__('No Results were found'));
        }
        // $post['result'] = json_decode($post['result'], true);
        // $key = [];
        // foreach ($post['result'] as $val) {
        //     if (isset($val['key'])) {
        //         $vk = (int) $val['key'];
        //         $key[$vk] = $vk;
        //     }
        // }
        // if (count($key) > 0 && count($key) != count($post['result'])) {
        //     $this->error(__('Invalid parameters'));
        // }
        // var_dump($_POST);die;

        // var_dump($post);die;
        // halt($post['row']);
        try {
            Db::startTrans();
            //处理问题
            $testson = new Testson();
            $testson->saveData($post['row'], $ids);
            //处理结果
            // $resModel = new Result();
            // $resModel->saveData($post['result'], $ids);
            Db::commit();
            $this->success();
        } catch (Exception $e) {
            Db::rollback();
            $this->error(__($e->getMessage()), $e->getCode());
        }
    }

    /**
     * 编辑
     */
    public function edit_dimension($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $testson = new Testson();
        $question = $testson->with('Question')->where('main_id', '=', $ids)->select()->toArray();

        // var_dump($question);die;
        $dimensionArr = [];
        foreach ($question as $k => $v) {
            foreach ($v['question_text'] as $kk => $vv) {
                if (!array_key_exists($vv['dimension'], $dimensionArr)) {
                    $dimensionArr[$vv['dimension']] = '';
                }
            }
        }
        // var_dump($dimensionArr);die;
        $aaa = $row['dimensionArr'] ? json_decode($row['dimensionArr']) : [];
        $arr = [];
        foreach ($dimensionArr as $k => $v) {

            $is = true;
            foreach ($aaa as $kk => $vv) {
                if ($vv->key == $k) {
                    $arr[$kk] = $vv;
                    $is = false;
                }
            }
            // var_dump($is);
            if ($is) {
                // var_dump($k);
                $arr[] = [
                    'key' => $k,
                    'name' => '',
                ];
            }
        }
        // var_dump($arr);die;
        $json = json_encode($arr);

        $row['dimensionArr'] = $json;


        // $row['multiplejson']='[{"title":"标题一","intro":"介绍一","author":"小明","age":"21"},{"title":"2","intro":"3","author":"4","age":"4"}]';
        // var_dump($row);die;
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }


    public function copy()
    {
        $params = $this->request->param();
        $ids = $params['ids'];

        $testMainList = $this->model->whereIn('id', $ids)->select()->toArray();


        // 启动事务
        Db::startTrans();
        try {

            foreach ($testMainList as $v) {
                $mentaTlestreportList = \think\Db::name('mental_testreport')->where('main_id', $v['id'])->select();
                $mainArr = $v;
                unset($mainArr['id']);
                unset($mainArr['type_text']);
                unset($mainArr['pay_mode_text']);
                $mainArr['createtime'] = time();
                $mainArr['updatetime'] = time();


                $mainId = \think\Db::name('mental_testmain')->insertGetId($mainArr);

                foreach ($mentaTlestreportList as $vv) {
                    $data = $vv;
                    unset($data['id']);
                    $data['main_id'] = $mainId;
                    $data['createtime'] = time();
                    \think\Db::name('mental_testreport')->insert($data);
                }
            }




            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            var_dump($e->getMessage());
            die;
        }

        $this->success('复制成功');
    }



    /**
     * 规则设置
     * 4=scl90规则
     */
    public function ruleconfig($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $ruleConfig = json_decode($row->ruleConfig, true);
        $dimensionArr = json_decode($row->dimensionArr, true);
        foreach ($dimensionArr as $k => $v) {
            $dimensionArr[$k]['s1'] = $ruleConfig['yzf'][$v['key']]['s1'];
            $dimensionArr[$k]['s2'] = $ruleConfig['yzf'][$v['key']]['s2'];
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);
                $params1 = ['ruleConfig'=>json_encode($params)];
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params1);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("dimensionArr", $dimensionArr);
        $this->view->assign("ruleConfig", $ruleConfig);

        return $this->view->fetch();
    }
}
